//
//  topLineViewController.swift
//  hEhL
//
//  Created by 本 on 16/5/8.
//  Copyright © 2016年 本. All rights reserved.
//

import UIKit
let CELLID = "CELLID"

class topLineViewController: UIViewController {


   @IBOutlet weak var tableView: UITableView!
    var downLoadData = NSData()
    lazy var ADView = ABInfiniteScrollView()
    private lazy var lineModel : [ABTopLineModel] = [ABTopLineModel]()
    private lazy var HeadModel : [AnyObject] = [AnyObject]()
    var isDownLoad: Bool = false
    private lazy var fullPath : String =  {
        let str =  NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true)[0]
    
        return str
    }()
//    print(fullPath)
    lazy var itemArray = [[String: AnyObject]]()
    lazy var BmView = UIView()
    lazy var headArray = [[String: AnyObject]]()
     var page = 1
     var count = 26
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.contentInset = UIEdgeInsetsMake(35, 0, 64, 0)
    
        self.tableView.scrollIndicatorInsets = UIEdgeInsetsMake(235, 0,44, 0)
        setupScrollView()
        setupBmView()
        
        
        
        setupRefresh()
        

        
        tableView.registerNib(UINib(nibName: "topLineCell", bundle: nil), forCellReuseIdentifier: CELLID)

    }
    
    /**
     快速创建xib
     
     - returns: 返回
     */
    class func initWithNib()->topLineViewController{
        return NSBundle.mainBundle().loadNibNamed("topLineViewController", owner: nil, options: nil).first as! topLineViewController
    

    }
}
extension topLineViewController : UITableViewDataSource,UITableViewDelegate{
   
//    override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
//        let cView = ABCollectionView()
//        cView.frame = CGRectMake(0, 0, self.view.frame.size.width, 75)
//        return cView
//
//    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return self.lineModel.count
    }
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
       
        let cell = tableView.dequeueReusableCellWithIdentifier(CELLID, forIndexPath: indexPath) as! topLineCell

       
        cell.model = self.lineModel[indexPath.row]
        if indexPath.row  == count * page - page {
            self.page += 1
            setupNetWork()
        }
        
        

        return cell
    }
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 120
    }
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
        let model = self.lineModel[indexPath.row]
        let webView = ABWebViewController()
        webView.url = NSURL(string: model.destUrl)

        
        self.navigationController?.pushViewController(webView, animated: true)

    }


}
extension topLineViewController{
    func setupNetWork(){
        if isDownLoad == true{return}
        print(self.fullPath)
        
        
        let manager = AFHTTPSessionManager()
        var dic = [String: AnyObject]()
        isDownLoad = true
        dic["action"] = "l"
        dic["newsTag"] = "headlineNews"
        dic["p"] = self.page
//        http://box.dwstatic.com/apiNewsList.php?action=l&newsTag=headlineNews&p=1
        manager.GET("http://box.dwstatic.com/apiNewsList.php", parameters: dic, progress: nil, success: { (test: NSURLSessionDataTask, data: AnyObject?) -> Void in
            guard let data1 = data else{return}
            self.downLoadData = self.exchangeData(data1 as! NSDictionary)
            self.downLoadData.writeToFile(self.fullPath, atomically: true)

            
           self.dealCache(data1)
            
//
            
                self.dealData(data1)
                self.dealHeadData(data1)
            self.isDownLoad = false
            self.tableView.mj_header.endRefreshing()
            
            }) { (tast: NSURLSessionDataTask?, error: NSError) -> Void in
                print(error)
        }
    }
    func dealData(data: AnyObject){
        guard let dic = data as? [String: AnyObject] else{
            return
        }
        guard let dicItem = dic["data"] as? [[String: AnyObject]] else {return}

        if self.page == 1{
            self.lineModel = [ABTopLineModel]()
        }
        
        for item in dicItem{
            
            let model = ABTopLineModel(dict: item)
            self.lineModel.append(model)
        }
        
        self.tableView.reloadData()
    }
    func dealHeadData(data: AnyObject){
        guard let dic = data as? [String: AnyObject] else{
            return
        }
        guard let dicItem = dic["headerline"] as? [[String: AnyObject]] else {return}
        if self.headArray == dicItem {return}
            self.HeadModel = [AnyObject]()
        for item in dicItem{
            
            let model = headViewModel(dic: item)
            let url = NSURL(string: model.photo)
            guard let urlR = url else{return}
            self.HeadModel.append(urlR)
            
        }

        self.ADView.images = self.HeadModel


        self.tableView.reloadData()

    }
  
}
extension topLineViewController{
    func setupScrollView(){


        let adView = ABInfiniteScrollView.init(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, 200))

//        headView.frame = CGRectMake(0, 0, tableView.frame.size.width, 200)
        self.tableView.tableHeaderView = adView
        self.ADView = adView
//        self.headView = headView
//        tableView.addSubview(adView)
    
        
    }
    func setupRefresh(){
    
//        __unsafe_unretained __typeof(self)weakSelf = self;

        //
        //        // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
        //        self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        //            [weakSelf loadNewData];
        //            }];
        //
        //        // 马上进入刷新状态
        //        [self.tableView.mj_header beginRefreshing];
        //        self.tableView.mj_header = MJRefreshNormalHeader(refreshingBlock: self.setupNetWork)
        //        self.tableView.mj_header.beginRefreshing()
        self.tableView.mj_header = MJRefreshNormalHeader(refreshingBlock: { () -> Void in
            self.page = 1
            self.setupNetWork()
        })
        self.tableView.mj_header.beginRefreshing()
    }
    func setupBmView(){
        let BmView = UILabel()
        BmView.frame = CGRectMake(0, 0, tableView.frame.size.width, 44)
        BmView.text = "ganbadie"
        self.BmView = BmView
        tableView.addSubview(BmView)
        self.tableView.tableFooterView = BmView
    
    }
//    func setupNoti(){
//        NSNotificationCenter.defaultCenter().addObserver(self, selector: "reloadData", name: "ABReLoadData", object: nil)
//        
//    }
//    func reloadData(){
//        self.tableView.reloadData()
//    }
    

}
extension topLineViewController{
    func dealCache(data: AnyObject){
//        guard let dic = data as? [NSObject: AnyObject] else{return}
//        var dic1 = NSDictionary()
//        dic1 = dic
//        dic1 = ABDealData.dealData(dic1 as! [NSObject: AnyObject])
        

    
    }
    func exchangeData (dic:NSDictionary) ->NSData{
            let data = NSMutableData()
            let archiver = NSKeyedArchiver(forWritingWithMutableData: data)
            archiver.encodeObject(dic, forKey: "lolData")
            archiver.finishEncoding()
            return data
        
        }
    }
